package com.gree.framework.config;

import com.gree.common.entity.SysApiRoleVo;
import com.gree.common.service.SysApiRoleService;
import com.gree.common.utils.StringUtils;
import com.gree.common.utils.spring.SpringxUtils;
import com.gree.framework.utils.SecurityUtils;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;

@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher antPathMatcher = new AntPathMatcher();


    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //进来都是调用auth2模块通过用户验证的请求
        //获取请求地址
        String requestUrl = ((FilterInvocation) o).getRequestUrl();

        HttpServletRequest httpServletRequest = ((FilterInvocation) o).getRequest();
        String url = httpServletRequest.getHeader("absoluteurl");

        if (skipAuthenticationCheck(url)){
            return null;
        }

        if (antPathMatcher.match("/**/swagger-resources/**", url)
                ||antPathMatcher.match("/**/api-docs", url)
                ||antPathMatcher.match("/**/swagger-resources", url)
        ){
            return null;
        }

        String token = httpServletRequest.getHeader("x-authorization");
        SysApiRoleVo sysApiRoleVo1 = new SysApiRoleVo();
        SysApiRoleService sysApiRoleService = SpringxUtils.getBean(SysApiRoleService.class);
        List<SysApiRoleVo> sysApiRoleVos1 = sysApiRoleService.querySysApiRole(sysApiRoleVo1);

        SysApiRoleVo sysApiRoleVo2 = null;
        for(SysApiRoleVo sysApiRoleVo:sysApiRoleVos1){
            if(antPathMatcher.match(sysApiRoleVo.getApiurl(),url)){
                sysApiRoleVo2 = sysApiRoleVo;
            }
        }

        String clientId = "";

        OAuth2Authentication oAuth2Authentication = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication instanceof OAuth2Authentication){
            oAuth2Authentication = (OAuth2Authentication)authentication;
            LinkedHashMap<String,Object> map = (LinkedHashMap<String, Object>) oAuth2Authentication.getUserAuthentication().getDetails();
            clientId = map.get("client_id")==null?"":map.get("client_id").toString();
        }


        if(sysApiRoleVo2 != null){
            int type = sysApiRoleVo2.getType();
            if(type != 4){
                if(clientId.equals("gscmex_client")){
                    if(!url.equals("/microservice-auth3/users/current")){
                        return SecurityConfig.createList("ROLE_LOGIN");
                    }else{
                        String[] values = new String[1];
                        values[0] = "GSCMAD";
                        return SecurityConfig.createList(values);
                    }
                }
            }

            if(type == 1){
                return null;
            }else if(type == 2){
                if(StringUtils.isNotEmpty(token) && token.equals(sysApiRoleVo2.getToken())){
                    return null;
                }
            }else if(type == 3){
                String[] values = sysApiRoleVo2.getRoid().split(",");
                return SecurityConfig.createList(values);
            }else if(type == 4){
                if(clientId.equals("gscmex_client") || (clientId.equals("gscm_client"))){
                    return null;
                }
            }else if(type == 5){
                if(clientId.equals("gscm_client")) {
                    String[] values = new String[1];
                    values[0] = "GSCMAD";
                    return SecurityConfig.createList(values);
                }else{
                    String username = SecurityUtils.getUser().getUsername();
                    if(Arrays.asList(sysApiRoleVo2.getUsers()).contains(username)){
                        return null;
                    }
                }
            }
        }else{
            if(clientId.equals("gscmex_client")){
                if(!url.equals("/microservice-auth3/users/current")){
                    return SecurityConfig.createList("ROLE_LOGIN");
                }else{
                    String[] values = new String[1];
                    values[0] = "GSCMAD";
                    return SecurityConfig.createList(values);
                }
            }else if(clientId.equals("external_client")){
                if(url.equals("/microservice-auth3/users/current")){
                    return null;
                }
            }else if(clientId.equals("external_client1")){
                if(url.equals("/microservice-auth3/users/current")){
                    return null;
                }
            }else if(clientId.equals("saas_client")){
                return null;
            }else {
                String[] values = new String[1];
                values[0] = "GSCMAD";
                return SecurityConfig.createList(values);
            }
        }

        //没有匹配上的资源，都是登录访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

    //TODO String... antPatterns
    private boolean customMatcher(String requestUrl,String... antPatterns) {
        boolean result= false;
        String[] var4 = antPatterns;
        int var5 = antPatterns.length;
        for(int var6 = 0; var6 < var5; ++var6) {
            String pattern = var4[var6];
            result = antPathMatcher.match(pattern,requestUrl);
            if(result){
                break;
            }
        }
        return result;

    }

    private boolean customMatcher2(String requestUrl,String requestMethod,List<SysApiRoleVo> sysApiRoleVos) {
        boolean result= false;
        for(SysApiRoleVo sysApiRoleVo:sysApiRoleVos) {
            String pattern = sysApiRoleVo.getApiurl();
            result = antPathMatcher.match(pattern,requestUrl);
            if(result){
                break;
            }
        }
        return result;
    }

    /**
     * 过滤静态资源
     */
    protected boolean skipAuthenticationCheck(String url) {
        return url.endsWith(".css") ||
                url.endsWith(".js") ||
                url.endsWith(".html") ||
                url.endsWith(".map") ||
                url.endsWith(".woff") ||
                url.endsWith(".png") ||
                url.endsWith(".jpg") ||
                url.endsWith(".jpeg") ||
                url.endsWith(".tif") ||
                url.endsWith(".tiff") ||
                url.endsWith(".json") ||
                url.endsWith(".xml");
    }
}
